//
//  SentenceToSenConfigVC.swift
//  Game
//
//  Created by woniu on 2025/9/12.
//

import Foundation
import UIKit
import SnapKit

class SentenceToSenConfigVC: UIViewController {
    public var gameModel:GameModel!
    public var onSubmitBlock: (()->())?
    
    private let nameField = UITextField()
    private var tableView: UITableView!
    private var addButton: UIButton!
    private var saveButton: UIButton!

    private var inputItemList:[SentenceItem] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.title = "配置"
        // 返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(onBack))
        navigationController?.navigationBar.tintColor = Colors.title
        if gameModel == nil{
            gameModel = GameModel.defaultSentenceToSModel()
        }
        let itemList = gameModel.jsonData.getArrayFromJSONString()
        for item in itemList{
            if let itemDic = item as? [String:Any]{
                let itemModel = SentenceItem.deserialize(from: itemDic) ?? SentenceItem()
                inputItemList.append(itemModel)
            }
        }
        setupUI()
    }
    
    @objc private func onBack() {
        if let nav = navigationController {
            nav.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }

    private func setupUI() {
        
        //名称背景
        let nameCard = UIView()
        nameCard.backgroundColor = .white
        view.addSubview(nameCard)
        nameCard.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(16)
            make.left.equalToSuperview().offset(45)
            make.right.equalToSuperview().offset(-45)
            make.height.equalTo(120)
        }
        
        let nameLab = UILabel()
        nameLab.text = "名字描述"
        nameLab.font = UIFont.boldSystemFont(ofSize: 20)
        nameLab.textColor = Colors.title
        nameCard.addSubview(nameLab)
        nameLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        nameField.placeholder = "添加名字、描述"
        nameField.text = gameModel.name
        nameField.leftViewMode = .always
        nameField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 40))
        nameField.rightViewMode = .always
        nameField.clearButtonMode = .unlessEditing
        nameField.textColor = .black
        nameField.circular(28)
        nameField.borderSet(Colors.blue.withAlphaComponent(0.4), 2)
        nameField.font = UIFont.systemFont(ofSize: 17)
        nameCard.addSubview(nameField)
        nameField.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(8)
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(nameLab.snp.bottom).offset(10)
            make.height.equalTo(56)
        }
        
        
        tableView = UITableView(frame: .zero, style: .plain)
        tableView.register(SentenceAnswerInputCell.self, forCellReuseIdentifier: SentenceAnswerInputCell.reuseIdentifier)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.rowHeight = 70
        view.addSubview(tableView)

        addButton = UIButton(type: .system)
        addButton.setTitle("添加一行", for: .normal)
        addButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        addButton.backgroundColor = Colors.blue
        addButton.setTitleColor(.white, for: .normal)
        addButton.layer.cornerRadius = 10
        addButton.addTarget(self, action: #selector(onAddRow), for: .touchUpInside)
        view.addSubview(addButton)

        saveButton = UIButton(type: .system)
        saveButton.setTitle("保存并关闭", for: .normal)
        saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        saveButton.backgroundColor = Colors.green
        saveButton.setTitleColor(.white, for: .normal)
        saveButton.layer.cornerRadius = 10
        saveButton.addTarget(self, action: #selector(onSave), for: .touchUpInside)
        view.addSubview(saveButton)

        // 布局 (针对 iPad 风格，留白较多)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(nameCard.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(40)
            make.right.equalToSuperview().offset(-40)
            make.bottom.equalTo(addButton.snp.top).offset(-20)
        }

        addButton.snp.makeConstraints { make in
            make.left.equalTo(tableView)
            make.height.equalTo(50)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            make.width.equalTo(160)
        }

        saveButton.snp.makeConstraints { make in
            make.right.equalTo(tableView)
            make.height.equalTo(50)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            make.width.equalTo(160)
        }
    }

    @objc private func onAddRow() {
        inputItemList.append(SentenceItem())
        tableView.reloadData()
        // 滚动到最后一行
        let last = inputItemList.count - 1
        if last >= 0 {
            tableView.scrollToRow(at: IndexPath(row: last, section: 0), at: .bottom, animated: true)
        }
    }

    @objc private func onSave() {
        let name = nameField.text ?? ""
        if name.isEmpty{
            Utils.alert(msg: "请输入名称、描述")
            return
        }
        gameModel.name = name
        // 打印不为空的元素
        let realList = inputItemList.filter { item in
            let topic = item.topic.replaceRN()
            let answer = item.answer.replaceRN()
            return !topic.isEmpty && !answer.isEmpty
        }
        if realList.isEmpty{
            Utils.alert(msg: "请填入信息再提交")
            return
        }
        let json = realList.toJSONString() ?? ""
        gameModel.jsonData = json
        
        print("保存的数据:\(gameModel.toJSONString() ?? "")")
        GameManager.share.insertOrUpdate(game: gameModel)
        onSubmitBlock?()
        self.navigationController?.popViewController(animated: true)
    }
}

extension SentenceToSenConfigVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return inputItemList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SentenceAnswerInputCell.reuseIdentifier, for: indexPath) as! SentenceAnswerInputCell
        
        let item = inputItemList[indexPath.row]
        cell.updateUI(item: item, index: indexPath.row+1)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
